import taichi as ti

from .plane import Plane
from ..utils import Inf, Ray3


class Rectangle2d(Plane):
    """平面长方形"""

    def __init__(self, w: float = 1, h: float = None):
        super().__init__()
        h = w if h is None else h
        Plane.shapes[self.index].attribute[0] = w / 2
        Plane.shapes[self.index].attribute[1] = h / 2

    @ti.func
    def intersect(self: int, ray: Ray3, closest: float):
        w_2 = Plane.shapes[self].attribute[0]
        h_2 = Plane.shapes[self].attribute[1]
        root, norm = Plane.intersect(self, ray, closest)
        if root < closest:
            hitPos = ray.at(root)
            if abs(hitPos.x) > w_2 or abs(hitPos.y) > h_2:
                root = Inf
        return root, norm
